class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix)
    {
        int up = 0, down = matrix.size(), right = matrix[0].size(), left = -1,
            i = 0, j = -1, idx = 0, size = down * right;
        vector<int> ans(size);
        while(true)
        {
            while(j + 1 < right) ans[idx++] = matrix[i][++j]; --right;
            if(idx == size) break;
            while(i + 1 < down) ans[idx++] = matrix[++i][j]; --down;
            if(idx == size) break;
            while(j - 1 > left) ans[idx++] = matrix[i][--j]; ++left;
            if(idx == size) break;
            while(i - 1 > up) ans[idx++] = matrix[--i][j]; ++up;
            if(idx == size) break;
        }
        return ans;
    }
};